﻿using System.Collections.Generic;

namespace Basic
{
    /// <summary>
    /// DictionaryExtension
    /// </summary>
    public static class DictionaryExtension
    {
        /// <summary>
        /// 尝试从字典里获取指定键的值。如果不存在，则返回默认值。
        /// </summary>
        /// <typeparam name="TKey"></typeparam>
        /// <typeparam name="TValue"></typeparam>
        /// <param name="thisDict"></param>
        /// <param name="key"></param>
        /// <param name="defaultValueOnNotExist"></param>
        /// <param name="throwExceptionOnNotExist"></param>
        /// <returns></returns>
        public static TValue TryGet<TKey, TValue>(this Dictionary<TKey, TValue> @thisDict, TKey key, TValue defaultValueOnNotExist = default(TValue), bool throwExceptionOnNotExist = false)
        {
            TValue value;
            if (thisDict.TryGetValue(key, out value))
            {
                return value;
            }

            if (throwExceptionOnNotExist)
            {
                throw new System.Exception(string.Format("dict not contain key {0}", key));
            }

            return defaultValueOnNotExist;
        }
    }
}
